package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    private static final String SELECT_XPATHEXPRESSION = "//select";

    private static final String INSERT_XPATHEXPRESSION = "//insert";

    private static final String UPDATE_XPATHEXPRESSION = "//update";

    private static final String DELETE_XPATHEXPRESSION = "//delete";

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");
        parseEmement(rootElement, namespace, SELECT_XPATHEXPRESSION);
        parseEmement(rootElement, namespace, INSERT_XPATHEXPRESSION);
        parseEmement(rootElement, namespace, UPDATE_XPATHEXPRESSION);
        parseEmement(rootElement, namespace, DELETE_XPATHEXPRESSION);
    }

    private void parseEmement(Element rootElement, String namespace, String xpathExpression) {
        List<Element> list = rootElement.selectNodes(xpathExpression);
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            String statementType = element.getName();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setStatementType(statementType);
            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }


}
